import { getEquipmentModels } from '@/api/equipment-model'
import { getEquipmentTypes } from '@/api/equipment-type'
import { getEquipments } from '@/api/equipment'

const state = {
    equip_models: [],
    equip_types: [],
    equips: [],
    options: [],
}

const mutations = {
    SET_EQUIP_MODEL: (state, data) => {
        state.equip_models = data
    },
    SET_EQUIP_TYPE: (state, data) => {
        state.equip_types = data
    },
    SET_EQUIPS: (state, data) => {
        state.equips = data
    },
    SET_OPTIONS: (state, data) => {
        state.options = data
    },
}

const buildTree = (data) => {
    let result = [];
    if (!Array.isArray(data)) {
        return result;
    }
    data.forEach((item) => {
        delete item.children;
    });
    let map = {};
    data.forEach((item) => {
        map[item.equipmentTypeID] = {
            value: item.equipmentTypeID,
            label: item.name
        }
    });
    data.forEach((item) => {
        let parent = map[item.parentID]
        if (parent) {
            (parent.children || (parent.children = [])).push(map[item.equipmentTypeID]);
        } else {
            result.push(map[item.equipmentTypeID])
        }
    });
    return result;
}

const actions = {
    getEquipModels: ({ commit }, params) => {
        return new Promise((resolve, reject) => {
            getEquipmentModels(params)
                .then(res => {
                    const { data } = res
                    commit("SET_EQUIP_MODEL", data)
                    resolve(data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
    getEquipTypes: ({ commit }, params) => {
        return new Promise((resolve, reject) => {
            getEquipmentTypes(params)
                .then(res => {
                    const { data } = res
                    commit('SET_EQUIP_TYPE', data)
                    commit('SET_OPTIONS', buildTree(data))
                    resolve(data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
    getEquips: ({ commit }, params) => {
        return new Promise((resolve, reject) => {
            getEquipments(params)
                .then(res => {
                    const { data } = res
                    commit('SET_EQUIPS', data)
                    resolve(data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}